package com.anlu.activemq.test1;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

public class CdProducer {

    //默认连接用户名
    private static final String USERNAME
            = ActiveMQConnection.DEFAULT_USER;
    //默认连接密码
    private static final String PASSWORD
            = ActiveMQConnection.DEFAULT_PASSWORD;
    //默认连接地址
    private static final String BROKEURL
            = ActiveMQConnection.DEFAULT_BROKER_URL;
    //发送的消息数量
    private static final int SENDNUM = 10;

    public static void main(String[] args) {
        ConnectionFactory connectionFactory = null;
        Connection connection=null;
        Session session;
        Destination destination;
        MessageProducer messageProducer;

        connectionFactory=new ActiveMQConnectionFactory(USERNAME,PASSWORD,BROKEURL);

        try{
            connection = connectionFactory.createConnection();
            connection.start();

            /**
             *  paramA是设置事务的，paramB设置acknowledgment mode 
             * paramA设置为false时：paramB的值可为Session.AUTO_ACKNOWLEDGE，Session.CLIENT_ACKNOWLEDGE，DUPS_OK_ACKNOWLEDGE其中一个。 
             * paramA设置为true时：paramB的值忽略， acknowledgment mode被jms服务器设置为SESSION_TRANSACTED 。 
             * Session.AUTO_ACKNOWLEDGE为自动确认，客户端发送和接收消息不需要做额外的工作。 
             * Session.CLIENT_ACKNOWLEDGE为客户端确认。客户端接收到消息后，必须调用javax.jms.Message的acknowledge方法。jms服务器才会删除消息。 
             * DUPS_OK_ACKNOWLEDGE允许副本的确认模式。一旦接收方应用程序的方法调用从处理消息处返回，会话对象就会确认消息的接收；而且允许重复确认。在需要考虑资源使用时，这种模式非常有效。
             */
            session=connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
//            destination=session.createQueue("anlu3.queue,topic://anlu.mark");
            destination=session.createTopic("anlu.test.topic");
            messageProducer=session.createProducer(destination);

            for (int i=0;i<SENDNUM;i++){
                String msg = "AL_Producer "+i+" "+System.currentTimeMillis();
                TextMessage message =session.createTextMessage(msg);
                System.out.println("发送消息:"+msg);
                messageProducer.send(message);
            }
            session.commit();

        }catch (JMSException e){
            e.printStackTrace();
        }finally {
            if(connection!=null){
                try{
                    connection.close();
                }catch (JMSException e){
                    e.printStackTrace();
                }
            }
        }



    }

}
